<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>申请详情 - 售后管理系统</title>
  <link rel="stylesheet" href="/after_sale_system/css/common.css">
  <style>
    .detail-container {
      background-color: white;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      margin-bottom: 20px;
    }

    .detail-header {
      border-bottom: 1px solid #eee;
      padding-bottom: 15px;
      margin-bottom: 15px;
    }

    .detail-title {
      font-size: 18px;
      font-weight: 500;
      margin-bottom: 10px;
    }

    .status-tag {
      display: inline-block;
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 14px;
      font-weight: 500;
    }

    .status-pending_audit {
      background-color: #fff3cd;
      color: #856404;
    }

    .status-processing {
      background-color: #d1ecf1;
      color: #0c5460;
    }

    .status-resolved {
      background-color: #d4edda;
      color: #155724;
    }

    .status-rejected {
      background-color: #f8d7da;
      color: #721c24;
    }

    .detail-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
      gap: 15px;
      margin-bottom: 20px;
    }

    .detail-item {
      display: flex;
      flex-direction: column;
    }

    .detail-label {
      font-size: 14px;
      color: #666;
      margin-bottom: 4px;
    }

    .detail-value {
      font-weight: 500;
    }

    .evidence-section {
      margin: 20px 0;
    }

    .evidence-title {
      font-weight: 500;
      margin-bottom: 10px;
    }

    .evidence-list {
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
    }

    .evidence-item {
      width: 120px;
      height: 120px;
      border: 1px solid #eee;
      border-radius: 4px;
      overflow: hidden;
      cursor: pointer;
    }

    .evidence-item img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .communication-section {
      margin-top: 30px;
    }

    .communication-title {
      font-weight: 500;
      margin-bottom: 15px;
    }

    .message-list {
      border: 1px solid #eee;
      border-radius: 8px;
      padding: 15px;
      height: 300px;
      overflow-y: auto;
      margin-bottom: 15px;
    }

    .message-item {
      margin-bottom: 15px;
      max-width: 70%;
    }

    .message-sender {
      font-size: 12px;
      color: #666;
      margin-bottom: 4px;
    }

    .message-content {
      padding: 10px 15px;
      border-radius: 8px;
      word-wrap: break-word;
    }

    .message-customer {
      background-color: #e9f5ff;
      margin-right: auto;
    }

    .message-service {
      background-color: #f0f7ff;
      margin-left: auto;
    }

    .reply-box {
      display: flex;
      gap: 10px;
    }

    .reply-input {
      flex: 1;
      padding: 10px;
      border: 1px solid #ddd;
      border-radius: 4px;
      resize: none;
      height: 80px;
    }

    .btn-send {
      padding: 8px 16px;
      background-color: #667eea;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      align-self: flex-end;
    }

    .audit-section {
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #eee;
    }
  </style>
</head>
<body>
<div class="header">
  <h1>售后管理系统 - 客服端</h1>
  <div class="user-info">
    <span>欢迎，<span id="username">客服</span></span>
    <a href="/login" class="logout-btn">退出登录</a>
  </div>
</div>

<div class="container">
  <div class="nav-menu">
    <h2>功能菜单</h2>
    <div class="nav-grid">
      <a href="/after_sale_system/page/customerService/applicationList" class="nav-item">
        <h3>申请审核</h3>
        <p>审核售后申请</p>
      </a>
      <a href="/after_sale_system/page/customerService/workOrder" class="nav-item">
        <h3>工单处理</h3>
        <p>处理售后工单</p>
      </a>
    </div>
  </div>

  <div class="content">
    <div class="detail-container">
      <div class="detail-header">
        <div class="detail-title">售后申请 #<span id="applicationId"></span></div>
        <div>
          状态: <span class="status-tag" id="statusTag"></span>
        </div>
      </div>

      <div class="detail-grid">
        <div class="detail-item">
          <span class="detail-label">用户ID</span>
          <span class="detail-value" id="userId"></span>
        </div>
        <div class="detail-item">
          <span class="detail-label">订单号</span>
          <span class="detail-value" id="orderId"></span>
        </div>
        <div class="detail-item">
          <span class="detail-label">商品名称</span>
          <span class="detail-value" id="productName"></span>
        </div>
        <div class="detail-item">
          <span class="detail-label">申请类型</span>
          <span class="detail-value" id="afterSaleType"></span>
        </div>
        <div class="detail-item">
          <span class="detail-label">申请时间</span>
          <span class="detail-value" id="applyTime"></span>
        </div>
        <div class="detail-item">
          <span class="detail-label">审核时间</span>
          <span class="detail-value" id="auditTime"></span>
        </div>
      </div>

      <div class="detail-item">
        <span class="detail-label">申请说明</span>
        <div class="detail-value" id="description" style="white-space: pre-line;"></div>
      </div>

      <div class="evidence-section">
        <div class="evidence-title">凭证图片</div>
        <div class="evidence-list" id="evidenceList">
          <!-- 凭证图片将通过JavaScript动态加载 -->
        </div>
      </div>

      <div class="detail-item" id="rejectReasonSection" style="display: none;">
        <span class="detail-label">拒绝原因</span>
        <div class="detail-value" id="rejectReason"></div>
      </div>
    </div>

    <div class="communication-section">
      <div class="communication-title">沟通记录</div>
      <div class="message-list" id="messageList">
        <!-- 消息记录将通过JavaScript动态加载 -->
      </div>
      <div class="reply-box">
        <textarea class="reply-input" id="replyContent" placeholder="输入回复内容..."></textarea>
        <button class="btn-send" id="sendBtn">发送</button>
      </div>
    </div>
  </div>
</div>

<script src="/after_sale_system/js/common.js"></script>
<script>
  // 获取URL中的申请ID
  const urlParams = new URLSearchParams(window.location.search);
  const applicationId = urlParams.get('id');

  document.addEventListener('DOMContentLoaded', function() {
    if (!applicationId) {
      showMessage('无效的申请ID', 'error');
      return;
    }

    loadApplicationDetail();
    loadCommunicationRecords();

    // 发送消息按钮事件
    document.getElementById('sendBtn').addEventListener('click', sendMessage);

    // 按Enter发送消息
    document.getElementById('replyContent').addEventListener('keydown', function(e) {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        sendMessage();
      }
    });
  });

  // 加载申请详情
  function loadApplicationDetail() {
    fetch(`/after_sale_system/api/afterSale/detail/${applicationId}`)
            .then(response => response.json())
            .then(data => {
              if (data.success) {
                const application = data.data;
                renderApplicationDetail(application);
              } else {
                showMessage(data.message, 'error');
              }
            })
            .catch(error => {
              showMessage('加载详情失败', 'error');
              console.error(error);
            });
  }

  // 渲染申请详情
  function renderApplicationDetail(application) {
    document.getElementById('applicationId').textContent = application.id;
    document.getElementById('userId').textContent = application.userId;
    document.getElementById('orderId').textContent = application.orderId;
    document.getElementById('productName').textContent = application.productName;
    document.getElementById('afterSaleType').textContent = formatAfterSaleType(application.afterSaleType);
    document.getElementById('applyTime').textContent = formatDateTime(application.applyTime);
    document.getElementById('description').textContent = application.applyReason || '无';

    // 设置状态标签
    const statusTag = document.getElementById('statusTag');
    statusTag.textContent = formatStatus(application.status);
    statusTag.className = `status-tag status-${application.status.toLowerCase()}`;

    // 审核时间
    document.getElementById('auditTime').textContent = application.auditTime ? formatDateTime(application.auditTime) : '未审核';

    // 拒绝原因（如果有）
    if (application.status === 'REJECTED' && application.rejectReason) {
      document.getElementById('rejectReasonSection').style.display = 'block';
      document.getElementById('rejectReason').textContent = application.rejectReason;
    }

    // 渲染凭证图片
    const evidenceList = document.getElementById('evidenceList');
    if (application.voucherUrls) {
      const urls = application.voucherUrls.split(',');
      urls.forEach(url => {
        if (url) {
          const evidenceItem = document.createElement('div');
          evidenceItem.className = 'evidence-item';
          evidenceItem.innerHTML = `<img src="${url}" alt="凭证图片" onclick="window.open('${url}', '_blank')">`;
          evidenceList.appendChild(evidenceItem);
        }
      });
    } else {
      evidenceList.innerHTML = '<div>无凭证图片</div>';
    }
  }

  // 加载沟通记录
  function loadCommunicationRecords() {
    fetch(`/after_sale_system/api/communication?applicationId=${applicationId}`)
            .then(response => response.json())
            .then(data => {
              if (data.success) {
                renderCommunicationRecords(data.data);
              } else {
                showMessage(data.message, 'error');
              }
            })
            .catch(error => {
              console.error('加载沟通记录失败', error);
            });
  }

  // 渲染沟通记录
  function renderCommunicationRecords(records) {
    const messageList = document.getElementById('messageList');
    messageList.innerHTML = '';

    if (records.length === 0) {
      messageList.innerHTML = '<div style="text-align:center; color:#999;">暂无沟通记录</div>';
      return;
    }

    records.forEach(record => {
      const messageItem = document.createElement('div');
      messageItem.className = 'message-item';

      const senderType = record.senderType === 'CONSUMER' ? '消费者' : '客服';
      const messageClass = record.senderType === 'CONSUMER' ? 'message-customer' : 'message-service';

      messageItem.innerHTML = `
                    <div class="message-sender">${senderType} · ${formatDateTime(record.sendTime)}</div>
                    <div class="message-content ${messageClass}">${record.content}</div>
                `;

      messageList.appendChild(messageItem);
    });

    // 滚动到底部
    messageList.scrollTop = messageList.scrollHeight;
  }

  // 发送消息
  function sendMessage() {
    const content = document.getElementById('replyContent').value.trim();
    if (!content) {
      showMessage('请输入消息内容', 'warning');
      return;
    }

    fetch('/after_sale_system/api/communication', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: `applicationId=${applicationId}&content=${encodeURIComponent(content)}&senderType=CUSTOMER_SERVICE`
    })
            .then(response => response.json())
            .then(data => {
              if (data.success) {
                document.getElementById('replyContent').value = '';
                loadCommunicationRecords(); // 重新加载消息列表
              } else {
                showMessage(data.message, 'error');
              }
            })
            .catch(error => {
              showMessage('发送失败，请重试', 'error');
              console.error(error);
            });
  }
</script>
</body>
</html>